package com.xiaoshuidi.cloud.module.member.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.xiaoshuidi.cloud.module.member.constant.Constant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
@RequiredArgsConstructor
public class CodeUtil {
    private final RedisTemplate redisTemplate;

    private final StringRedisTemplate stringRedisTemplate;

    public String nextCode(String prefix) {
        return nextCode(prefix, 6);
    }

    public String nextCode(String prefix, int randomLength) {
        String no = null;
        while (true) {
            String randomCode = RandomUtil.randomString(randomLength);
            no = StrUtil.format(prefix + "{}{}", DateUtil.format(new Date(), "yyMMdd"), randomCode).toUpperCase();
            if (redisTemplate.opsForValue().setIfAbsent("code:" + no, 0, 24, TimeUnit.HOURS)) {
                break;
            }
        }
        return no;
    }
    //根据优惠券类型 查询每天最大的顺序码
    public String queryMaxCouponCode(String key) {
        final Long couponCode = stringRedisTemplate.opsForValue().increment(key);
        stringRedisTemplate.expire(Constant.COUPON_CODE + key, RedisUtils.DEFAULT_EXPIRE, TimeUnit.SECONDS);
        return String.format("%05d", couponCode);
    }
}
